﻿namespace WLFramework.Validation
{

    using System;

    [AttributeUsage(AttributeTargets.Property)]
    public class TextLengthAttribute : ValidationAttribute
    {
        public int MinLen { get; set; }
        public int MaxLen { get; set; }
        public TextLengthAttribute(int minLength,int maxLength) :
            this(minLength,maxLength,"字段\'{0}\'的长度必须在" + minLength + "-" + maxLength + "之间")
        { 
        }

        public TextLengthAttribute(int minLength,int maxLength,string displayErrors)
            : this(minLength,maxLength,displayErrors, "请输入{0}")
        {
        }

        public TextLengthAttribute(int minLength,int maxLength,string displayErrors, string displayDefault)
        {
            this.MinLen = minLength;
            this.MaxLen = maxLength;
            this.ErrorMessage = displayErrors;
            this.DefaultMessage = displayDefault;
        }

        public override ValidatePriority Priority
        {
            get
            {
                return ValidatePriority.High;
            }
        }

        public override ValidateResult IsValid(object input, ValidateContext context)
        {
            int len = input.ToString().Length;
            if (len >= this.MinLen && len <= MaxLen)
            {
                return ValidateResult.Success;
            }
            else
            {
                return new ValidateResult(this.FormatErrorMessage(context.DisplayName));
            }
        }
    }
}
